#include "HomeServer.h"
#include "MyLogeer.h"
#include "todoTask.h"
#include "login_context.h"
#include <iostream>
#include <functional>
using std::cout;
using std::endl;

HomeServer::HomeServer(unsigned short port, const string &ip, int threadNum, int queSize)
    : _threadpool(threadNum, queSize), _server(port, ip)
{
    printf("HomeServer\n");
    using namespace std::placeholders;
    _server.setAllCallbacks(
        std::bind(&HomeServer::onConnection, this, _1),
        std::bind(&HomeServer::onMessage, this, _1),
        std::bind(&HomeServer::onClose, this, _1));
}
void HomeServer::start()
{
    _threadpool.start();
    _server.start();
}

void HomeServer::onConnection(TcpConnectionPtr conn)
{
    LogInfo("tcp %s has connected.\n", conn->toString().c_str());
}

void HomeServer::onMessage(TcpConnectionPtr conn)
{
    cout << "onMessage" << endl;
    Packet packet;
    LoginContext context;
    int ret = conn->readPacket(packet);
    cout << "read:" << ret << "bytes." << endl;
    cout << "packet.type" << packet._type << endl
         << "packet.length" << packet._length << endl
         << "packet.msg" << packet._msg << endl;
    switch(packet._type){
        case TASK_TYPE_LOGIN_SECTION1:
        {
            UserLoginSection1 userLogin1(conn,packet,context);
            _threadpool.addTask(std::bind(&UserLoginSection1::process,userLogin1));
        }
        break;
        case TASK_TYPE_LOGIN_SECTION2:
        {
            UserLoginSection2 userLogin2(conn,packet,context);
            _threadpool.addTask(std::bind(&UserLoginSection2::process,userLogin2));
        }
    }
}

void HomeServer::onClose(TcpConnectionPtr conn)
{
    LogInfo("tcp %s has closed.\n", conn->toString().c_str());
}